{extend name="app/shop/view/base.html"/}
{block name="resources"}
<style>
	.discount { display: flex; justify-content: space-between; height: 34px; line-height: 34px; padding: 5px 15px; background-color: #F6FBFD; border: 1px dashed #BCE8F1; }
	.exchange-type {padding: 0 20px; position: relative;}
	.exchange-type:hover {border: 1px solid #ff8143;}
	.exchange-selected {border-color: #ff8143!important;}
	.exchange-selected:after {
		content: "";
		display: inline-block;
		width: 20px;
		height: 20px;
		background-image: url(__STATIC__/img/selected.png);
		position: absolute;
		bottom: 0;
		right: 0;
	}
	.form-wrap {position: relative;}
	.custom-right {
		position: absolute;
		top: 20px;
		left: 900px;
	    padding: 20px 0;
	    box-sizing: border-box;
	    overflow: hidden;
	    background-color: #fff;
		height: 670px;
		width: 600px;
	}
	.custom-right .phone {
	    min-width: 280px;
	    height: 650px;
	    background: url(__STATIC__/img/quan.png) no-repeat center;
	    background-size: contain;
	    position: relative;
	    overflow: auto;
	    padding-top: 30px;
	    box-sizing: border-box;
	}
	
	.custom-right .phone h2 {
		position: absolute;
		left: 250px;
		top: 80px;
	}
	
	.item {
		position: absolute;
		top: 100px;
		left: 165px;
		width: 274px;
		height: 100px;
		display: flex;
		background: url(__STATIC__/img/quan_bj.png) no-repeat center;
		border-radius: 10px;
		align-items: stretch;
		overflow: hidden;
		font-size: 13px;
	}
	.item-base {
		position: relative;
		width: 65px;
		min-width: 65px;
		text-align: center;
		background-repeat: no-repeat;
		background-size: 100% 100%;
		padding: 10px 10px 0 10px;
	}
	
	.item-base p {
		display: inline-block;
	}
	
	.item .item-base .aaa {
		height: auto;
		position: relative;
		top: 50%;
		right: 5px;
		transform: translate(0, -50%);
	}
	
	
	
	.item-info {
		margin:0 20px 0 0;
		width: 100px;
	}
	
	.use_price {
		line-height: 1;
		color: #fff;
	}

	.use_condition {
		color: #fff;
		margin-top: 15px;
		font-size: 12px;
	}
	
	.use_title {
		margin-top: 10px !important;
	}
	
	.item-btn {
		width: 50px;
		min-width: 50px;
		align-self: center;
		position: relative;
	}
	.item-btn .btn{
		font-size: 12px;
		width: 40px;
		height: 24px;
		border-radius: 20px;
		line-height: 24px;
		margin-left: 20px;
		text-align: center;
		background-image: linear-gradient(to right, #fc6831, #ff4544);
		color: #fff;
	}
	
	.max_price {
		margin: 5px 0;
		padding-bottom: 5px;
		border-bottom: 1px dashed #d7d2d1;
		font-size: 12px;
	}
	.use_time span {display: inline-block;font-size: 12px; color: #909399;}
	.priceaaaa {
		font-size: 16px;
	}
	.thistitle {
		font-size: 14px;
	}
	.goods_num {padding-left: 20px;}
</style>
{/block}
{block name="main"}

<div class="layui-form form-wrap">

	<div class="layui-form-item">
		<label class="layui-form-label"><span class="required">*</span>优惠券名称：</label>
		<div class="layui-input-block">
			<input type="text" name="coupon_name" lay-verify="required" autocomplete="off" class="layui-input len-long" maxlength="15">
		</div>
	</div>

	<div class="layui-form">
		<div class="layui-form-item">
			<label class="layui-form-label">优惠券类型：</label>
			<div class="layui-input-block">
				<button class="layui-btn layui-btn-primary exchange-type exchange-selected" data-status="reward">满减</button>
				<button class="layui-btn layui-btn-primary exchange-type" data-status="discount">折扣</button>
				<input type="hidden" name="type" value="reward">
			</div>
		</div>
	</div>

	<div class="layui-form-item" id="coupon_type">
		<label class="layui-form-label"><span class="required">*</span>优惠券面额：</label>
		<div class="layui-input-block">
			<div class="layui-input-inline">
				<input type="number" name="money" min="0" lay-verify="required|number|money|coupon_money" autocomplete="off" class="layui-input len-short" >
			</div>
			<span class="layui-form-mid">元</span>
		</div>
		<div class="word-aux">
			<p>价格不能小于0，可保留两位小数</p>
		</div>
	</div>

	<div class="layui-form-item">
		<label class="layui-form-label"><span class="required">*</span>满多少元可以使用：</label>
		<div class="layui-input-block">
			<div class="layui-input-inline">
				<input type="number" name="at_least" min="0" lay-verify="required|number|money" autocomplete="off" class="layui-input len-short">
			</div>
			<span class="layui-form-mid">元</span>
		</div>
		<div class="word-aux">
			<p>价格不能小于0，无门槛请设为0</p>
		</div>
	</div>

	<div class="layui-form-item">
		<label class="layui-form-label">是否允许直接领取：</label>
		<div class="layui-input-block">
			<input type="checkbox" name="is_show" lay-filter="is_show" value="1" lay-skin="switch" checked />
		</div>
	</div>

	<div class="receive-limit">
		<div class="layui-form-item">
			<label class="layui-form-label"><span class="required">*</span>发放数量：</label>
			<div class="layui-input-block">
				<div class="layui-input-inline">
					<input type="number" name="count" lay-verify="count" autocomplete="off" class="layui-input len-short">
				</div>
				<span class="layui-form-mid">张</span>
			</div>
			<div class="word-aux">
				<p>优惠券发放数量，没有之后不能领取或发放，-1为不限制发放数量</p>
			</div>
		</div>

		<div class="layui-form-item">
			<label class="layui-form-label"><span class="required">*</span>最大领取数量：</label>
			<div class="layui-input-block">
				<div class="layui-input-inline">
					<input type="number" name="max_fetch" min="0" value="1" lay-verify="max" autocomplete="off" class="layui-input len-short">
				</div>
				<span class="layui-form-mid">张</span>
			</div>
			<div class="word-aux">
				<p>数量不能小于0，且必须为整数；设置为0时，可无限领取</p>
			</div>
		</div>
	</div>

	<div class="layui-form-item">
		<label class="layui-form-label img-upload-lable">优惠券图片：</label>
		<div class="layui-input-block img-upload">
			<div class="upload-img-block">
				<div class="upload-img-box">
					<div class="upload-default" id="couponImg">
						<div class="upload">
							<i class="iconfont iconshangchuan"></i>
							<p>点击上传</p>
						</div>
					</div>
					<div class="operation">
						<div>
							<i title="图片预览" class="iconfont iconreview js-preview" style="margin-right: 20px;"></i>
							<i title="删除图片" class="layui-icon layui-icon-delete js-delete" ></i>
						</div>
						<div class="replace_img js-replace">点击替换</div>
					</div>
					<input type="hidden" name="image" />
				</div>
			</div>
		</div>
		<div class="word-aux">
			<p>建议尺寸：325*95像素，图片上传默认不限制大小</p>
		</div>
	</div>

	<div class="layui-form-item">
		<label class="layui-form-label">有效期类型：</label>
		<div class="layui-input-block">
			<input type="radio" name="validity_type" value="0" lay-filter="filter" checked="checked" title="固定时间">
			<input type="radio" name="validity_type" value="1" lay-filter="filter" title="领取之日起">
			<input type="radio" name="validity_type" value="2" lay-filter="filter" title="长期有效">
		</div>
	</div>

	<div class="layui-form-item end-time validity-type validity-type-0">
		<label class="layui-form-label"></label>
		<div class="layui-input-block">
			<input type="text" name="end_time" lay-verify="time" id="end_time" class="layui-input len-mid" autocomplete="off" readonly>
		</div>
	</div>

	<div class="layui-form-item fixed-term validity-type validity-type-1" style="display: none">
		<label class="layui-form-label">领取之日起：</label>
		<div class="layui-input-block">
			<div class="layui-input-inline">
				<input type="number" min="1" max="365" value="10" name="fixed_term" lay-verify="days" autocomplete="off" class="layui-input len-short">
			</div>
			<span class="layui-form-mid">天有效</span>
		</div>
		<div class="word-aux">
			<p>不能小于0，且必须为整数</p>
		</div>
	</div>

	<div class="layui-form-item">
		<label class="layui-form-label"><span class="required">*</span>活动商品：</label>
		<div class="layui-input-block">
			<input type="radio" name="goods_type" lay-filter="goods_type" value="1" title="全部商品参与" checked>
			<input type="radio" name="goods_type" lay-filter="goods_type" value="2" title="指定商品参与">
		</div>
	</div>

	<div class="layui-form-item goods_list" style="display:none">
		<label class="layui-form-label"></label>
		<div class="layui-input-block">

			<table id="selected_goods_list"></table>
			<button class="layui-btn" onclick="addGoods()">选择商品</button>  <span class="goods_num">已选商品（<span id="goods_num" class="text-color">0</span>）</span>
		</div>
	</div>
	<input type="hidden" name="goods_ids">

	<div class="form-row">
		<button class="layui-btn" lay-submit lay-filter="save">保存</button>
		<button class="layui-btn layui-btn-primary" onclick="back()">返回</button>
		<a id="imageId"></a>
	</div>
	
	<div class="custom-right">
		<div class="phone">
			<div class="item">
				<div class="item-base">
					<div class="aaa">
						<div class="use_price">
							<span class="priceaaaa">￥__<span>
						</div>
						<div class="use_condition font-size-tag">满<span class="use_price2">__</span>元可用</div>
					</div>
				</div>
				<div class="item-info">
					<div class="use_title">
						<div class="thistitle">满减折扣券</div>
						<div class="max_price">全场商品</div>
					</div>
					<div class="use_time">
						<span class="time-aaa validity-type validity-type-0">有效期：</span>
						<span style="display: none;" class="time-bbb validity-type validity-type-1">有效期：领取之日起10天内有效</span>
						<span style="display: none;" class="validity-type validity-type-2">有效期：长期有效</span>
					</div>
				</div>
				<div class="item-btn">
					<div class="btn">领取</div>
				</div>
			</div>
		</div>
	</div>
</div>

<!-- 操作 -->
<script type="text/html" id="operation">
	<div class="table-btn">
		<a class="layui-btn" onclick="delGoods({{d.goods_id}})">删除</a>
	</div>
</script>
{/block}
{block name="script"}
<script>
    var submitRule, delRule;
    var goods_list = [], selectedGoodsId = [], goods_id=[],table;
	var saveData = null;
	var totalUploadNum = 0;
	var completeUploadNum = 0;
	var upload;

	$("body").on("change",'input[name="money"]',function(){
		let aa = $('input[name="money"]').val();
		$('.priceaaaa').html('￥' + aa)
	});
	
	$("body").on("change",'input[name="discount"]',function(){		
		let bb = $('input[name="discount"]').val();
		$('.pricebbbb').html(bb + ' 折 ')
	});
	
	$('input[name="at_least"]').change(function(){
		let cc = $('input[name="at_least"]').val();
		$('.use_price2').html(cc)
	});
	
	$('input[name="fixed_term"]').change(function(){
		var time_time = $('input[name="fixed_term"]').val();
		$('.time-bbb').html('有效期：领取之日起' + time_time + '日内有效');
	});
	
	$("body").on("change",'input[name="coupon_name"]',function(){
		let dd = $('input[name="coupon_name"]').val();
		$('.thistitle').html(dd)
	});

    layui.use(['form', 'laydate','form'], function() {
        var form = layui.form,
		laydate = layui.laydate,
		repeat_flag = false; //防重复标识
        currentDate = new Date();  //当前时间
        form.render();

        currentDate.setDate(currentDate.getDate() + 10);  //10天后的日期

		form.on('switch(is_show)', function (data) {
			if ($(data.elem).is(':checked')) {
				$('.receive-limit').show();
			} else {
				$('.receive-limit').hide();
			}
		});

        // 时间模块
        laydate.render({
            elem: '#end_time', //指定元素
            type: 'datetime',
            value: currentDate,
			done: function(value, date, endDate){
				$('.time-aaa').html('有效期：' + value);
			}
        });
		
		      var date = new Date(currentDate);
		      var y = date.getFullYear();
			  var m = date.getMonth() + 1;
			  m = m < 10 ? ('0' + m) : m;
			  var d = date.getDate();
		 	  d = d < 10 ? ('0' + d) : d;
		      var h = date.getHours();
			  var minute = date.getMinutes();
			  var second = date.getSeconds();
			  minute = minute < 10 ? ('0' + minute) : minute;
			  let time = y + '-' + m + '-' + d+' '+h+':'+minute+':'+second; 
		$('.time-aaa').html('有效期：' + time);
		var time_time = $('input[name="fixed_term"]').val();
		$('.time-bbb').html('有效期：领取之日起' + time_time + '日内有效');

        renderTable(goods_list); // 初始化表格

        //监听活动商品类型
        form.on('radio(goods_type)', function(data){
            var value = data.value;

            if(value == 1){
                $(".goods_list").hide();
				$('.max_price').html('全场商品');
            }
            if(value == 2){
                $(".goods_list").show();
				$('.max_price').html('指定商品');
            }
        });

        // 监听单选按钮
        form.on('radio(filter)', function(data) {
        	$('.validity-type').hide();
			$('.validity-type-' + data.value).show();
        });

        /**
         * 表单验证
         */
        form.verify({
            days: function(value) {
				var validity_type = $('[name="validity_type"]:checked').val();
				if (validity_type == 1) {
					if (value%1 != 0) {
						return '请输入整数';
					}
					if (value <= 0) {
						return '有效天数不能小于等于0';
					}
				}
            },
            number: function (value) {
                if (value < 0) {
                    return '请输入大于或等于0的数!'
                }
            },
            int: function (value) {
                if (value%1 != 0) {
                    return '请输入整数!'
                }
                if (value < 0) {
                    return '请输入大于0的数!'
                }
            },
            money: function (value) {
                var arrMen = value.split(".");
                var val = 0;
                if (arrMen.length == 2) {
                    val = arrMen[1];
                }
                if (val.length > 2) {
                    return '保留小数点后两位'
                }
            },
			coupon_money: function (value) {
				if(parseFloat(value) > 10000){
					return '优惠券面额不能大于10000'
				}
			},
            time: function(value) {
                var validity_type = $('[name="validity_type"]:checked').val();
                if (validity_type == 0) {
                    var now_time = (new Date()).getTime();
                    var end_time = (new Date(value)).getTime();
                    if (now_time > end_time) {
                        return '结束时间不能小于当前时间!'
                    }
                }
            },
            max: function(value) {
				if ($('[name="is_show"]').is(':checked')) {
					if (!/[\S]+/.test(value)) {
						return '请输入最大领取数量';
					}
					var _count = $("input[name=count]").val();
					if (_count != -1 && parseFloat(value) > parseFloat(_count)) {
						return '最大领取数量不能超过发放数量!';
					}
				}
            },
            fl: function(value, item) {
                var str = $(item).parents(".layui-form-item").find("label").text().split("*").join("");
                str = str.substring(0, str.length - 1);

                if (value < 1) {
                    return str + "不能小于1折";
                }

                if (value > 9.9) {
                    return str + "不能大于9.9折";
                }

                var arrMen = value.split(".");
                var val = 0;
                if (arrMen.length == 2) {
                    val = arrMen[1];
                }
                if (val.length > 2) {
                    return str + "最多可保留两位小数";
                }
            },
            count: function(value){
            	if ($('[name="is_show"]').is(':checked')) {
            		if (!/[\S]+/.test(value)) {
						return '请输入发放数量';
					}
					if (value%1 != 0) {
						return '请输入整数';
					}
					if (value == 0 || value < -1) {
						return '发放数量不能为0或小于-1';
					}
				}
            }
        });

		upload = new Upload({
			elem: '#couponImg',
			auto:false,
			bindAction:'#imageId',
			callback: function(res) {
				uploadComplete('image', res.data.pic_path);
			}
		});

		function uploadComplete(field, pic_path) {
			saveData.field[field] = pic_path;
			completeUploadNum += 1;
			if(completeUploadNum == totalUploadNum){
				saveFunc();
			}
		}

		function saveFunc(){
			var data = saveData;
			// 删除图片
			if(!data.field.image) upload.delete();

			$.ajax({
				url: ns.url("coupon://shop/coupon/add"),
				data: data.field,
				dataType: 'JSON',
				type: 'POST',
				success: function(res) {
					repeat_flag = false;

					if (res.code == 0) {
						layer.confirm('添加成功', {
							title:'操作提示',
							btn: ['返回列表', '继续添加'],
							closeBtn: 0,
							yes: function(){
								location.href = ns.url("coupon://shop/coupon/lists")
							},
							btn2: function() {
								location.href = ns.url("coupon://shop/coupon/add")
							}
						});
					}else{
						layer.msg(res.message);
					}
				}
			});
		}

        /**
         * 监听提交
         */
        form.on('submit(save)', function(data) {

            if (data.field.is_show == undefined) {
                data.field.is_show = 0;
            }

            if(data.field.goods_type != 1){
                if(data.field.goods_ids == ''){
                    layer.msg("请选择商品");
                    return;
                }
            }
            if (repeat_flag) return;
            repeat_flag = true;

			saveData = data;
			var obj = $("img.img_prev[data-prev='1']");
			totalUploadNum = obj.length;
			if(totalUploadNum > 0){
				obj.each(function(){
					var actionId = $(this).attr('data-action-id');
					$(actionId).click();
				})
			}else{
				saveFunc();
			}
        });

        submitRule = function() {
            var money = $("#money").val().trim(),
                discount_money = $("#discount_money").val().trim();

            if (Number(money) == "0" || Number(discount_money) == "0") {
                layer.msg("满减金额不能为空！", {icon: 5, anim: 6});
                return false;
            }
            if (Number(money) < 0 || Number(discount_money) < 0) {
                layer.msg("金额不能小于0！", {icon: 5, anim: 6});
                return false;
            }
            if (Number(money) * 100 % 1 != 0 || Number(discount_money) * 100 % 1 != 0) {
                layer.msg("金额最多保留小数点后两位！", {icon: 5, anim: 6});
                return false;
            }

            for (var i=0; i<$(".discount-box .discount").length; i++) {
                var money_num = $(".discount-box .discount").eq(i).find(".money-num").text();
                if (money == money_num) {
                    layer.msg("该金额规则已添加，不可重复添加！");
                    return false;
                }
            }

            var html = '<div class="discount form-row">'+
                '<div class="discount-con">'+
                '<p>单笔订单满<span class="required money-num">' + money + '</span>元，立减现金<span class="required discount_money-num">' + discount_money + '</span>元</p>'+
                '</div>'+
                '<div class="discount-del">'+
                '<button class="layui-btn" onclick="delRule(this)">删除</button>'+
                '</div>'+
                '</div>';
            $(".discount-box").append(html);
        };

        delRule = function(obj) {
            $(obj).parent().parent().remove();
        };

        $(".exchange-type").click(function() {
            $(this).addClass("exchange-selected");
            $(this).siblings("button").removeClass("exchange-selected");

            var type = $(this).attr('data-status');
			
            var current_type = $("input[name='type']").val();
            if(current_type == type){
                return false;
            }

            $("input[name='type']").val(type);

            var html = '';
            if(type == 'reward'){
                html += '<label class="layui-form-label"><span class="required">*</span>优惠券面额：</label>' +
						'<div class="layui-input-block">' +
							'<div class="layui-input-inline">' +
								'<input type="number" name="money" min="0" lay-verify="required|number|money" autocomplete="off" class="layui-input len-short">' +
							'</div>' +
							'<span class="layui-form-mid">元</span>' +
						'</div>' +
						'<div class="word-aux">' +
							'<p>价格不能小于0，可保留两位小数</p>' +
						'</div>';
						
                $('.discount_limit').remove();
				// $('body .pricebbbb').css("display","none");
				// $('body .priceaaaa').css("display","block");
				$("body").on("change",'input[name="money"]',function(){
					let aa = $('input[name="money"]').val();
					$('.priceaaaa').html('￥' + aa)
				});
			}

            if(type == 'discount'){
                html += '<label class="layui-form-label"><span class="required">*</span>优惠券折扣：</label>' +
                    '<div class="layui-input-block">' +
                    '<div class="layui-input-inline">' +
                    '<input type="number" name="discount" min="1" lay-verify="required|fl" autocomplete="off" class="layui-input len-short">' +
                    '</div>' +
                    '<span class="layui-form-mid">折</span>' +
                    '</div>' +
                    '<div class="word-aux">' +
                    '<p>优惠券折扣不能小于1折，且不可大于9.9折，可保留两位小数</p>' +
                    '</div>';

		    	var discount_limit = '';
                discount_limit += '<div class="layui-form-item discount_limit">' +
                    '<label class="layui-form-label">最多优惠：</label>' +
                    '<div class="layui-input-block">' +
                    '<div class="layui-input-inline">' +
                    '<input type="number" name="discount_limit" min="0" lay-verify="number|int" autocomplete="off" class="layui-input len-short">' +
                    '</div>' +
                    '<span class="layui-form-mid">元</span>' +
                    '</div>' +
                    '</div>';
                $('#coupon_type').after(discount_limit);
				// $('body .priceaaaa').css("display","none");
				// $('body .pricebbbb').css("display","block");
				$("body").on("change",'input[name="discount"]',function(){
					let bb = $('input[name="discount"]').val();
					$('.pricebbbb').html(bb + ' 折 ')
				});
            }
			$('#coupon_type').html(html);
        });

    });

    // 表格渲染
    function renderTable(goods_list) {
        //展示已知数据
        table = new Table({
            elem: '#selected_goods_list',
            cols: [
                [{
                    field: 'goods_name',
                    title: '商品名称',
                    unresize: 'false',
                    width: '50%'
                }, {
                    field: 'price',
                    title: '商品价格(元)',
                    unresize: 'false',
                    align: 'right',
                    width: '20%',
                    templet: function(data) {
                        return '￥' + data.price;
                    }
                }, {
                    field: 'goods_stock',
                    title: '库存',
                    unresize: 'false',
                    align: 'center',
                    width: '20%'
                }, {
                    title: '操作',
                    toolbar: '#operation',
                    unresize: 'false',
					align:'right'
                }],
            ],
            data: goods_list,
        });
    }

    // 删除选中商品
    function delGoods(id) {
        var i, j;
        $.each(goods_list, function(index, item) {
            var goods_id = item.goods_id;

            if (id == Number(goods_id)) {
                i = index;
            }
        });
        goods_list.splice(i, 1);
        renderTable(goods_list);

        $.each(selectedGoodsId, function(index, item) {
            if (id == Number(item)) {
                j = index;
            }
        });
        selectedGoodsId.splice(j, 1);
        goods_id = selectedGoodsId;
		$("#goods_num").html(selectedGoodsId.length);
        $("input[name='goods_ids']").val(goods_id.toString());
    }

    /* 商品 */
    function addGoods(){
        goodsSelect(function (res) {
			if (!res.length) return false;
			goods_id = [];
            for(var i=0;i<res.length;i++) {
                goods_id.push(res[i].goods_id);
                goods_list.push(res[i]);
            }

            renderTable(goods_list);
            $("input[name='goods_ids']").val(goods_id.toString());
            selectedGoodsId = goods_id;
			$("#goods_num").html(selectedGoodsId.length)
        },selectedGoodsId, {mode: "spu"});
		goods_list.splice(0,goods_list.length);
    }

    function back() {
        location.href = ns.url("coupon://shop/coupon/lists");
    }
</script>
{/block}